package com.lilicould.service;

import com.google.gson.Gson;
import com.lilicould.dao.CourseDao;
import com.lilicould.entity.Courses;
import com.lilicould.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

public class CourseService {
    public String getAllCourses() {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            // 获取映射器对象
            CourseDao courseDao = sqlSession.getMapper(CourseDao.class);

            // 调用方法获取数据
            Courses[] courses = courseDao.getAllCourses();
            // 若不为空返回数据
            if (courses != null){
                return new Gson().toJson(courses);
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public String addCourse(Courses  course) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            // 获取映射器对象
            CourseDao courseDao = sqlSession.getMapper(CourseDao.class);
            int result = courseDao.addCourse(course);
            if (result > 0) {
                // 提交事务
                sqlSession.commit();
                return null;
            }else {
                return new Gson().toJson("执行sql返回结果不大于0");
            }
        } catch (Exception e) {
            return new Gson().toJson(e.getMessage());
        }
    }

    public String deleteCourse(String courseId) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession()){
            // 获取映射器对象
            CourseDao courseDao = sqlSession.getMapper(CourseDao.class);
            int result = courseDao.deleteCourse(courseId);
            if (result > 0) {
                // 提交事务
                sqlSession.commit();
                return null;
            }else {
                return new Gson().toJson("执行sql返回结果不大于0");
            }
        }catch (Exception e) {
            // 捕获异常并返回错误信息
            return new Gson().toJson("欲删除课程ID：" + courseId + e.getMessage());
        }
    }
}
